/* Copyright 203-2115 AtomWare Technology Pty Limited
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 * The flowing information must be keep 
 * ContractImportor.java
 * business
 * 2013-3-5下午5:51:55
 * @author 屈甲康
 * QQ285799123
 * mailto:qujiakang@gmail.com
 */

package org.jackysoft.report.data;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.jackysoft.entity.ContractClient;
import org.jackysoft.entity.ContractDataItem;
import org.jackysoft.entity.ContractItem;
import org.jackysoft.entity.ContractType;
import org.jackysoft.entity.Product;
import org.jackysoft.report.ProductValidation;
import org.jackysoft.report.TradeType;
import org.jackysoft.service.ContractClientService;
import org.jackysoft.service.ProductService;
import org.jackysoft.util.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

@Component
public class ContractImportor extends
		AbstractDataImporter<Map<String, Collection<ContractItem>>> {

	@Autowired
	private ProductService pdtService;
	
	@Autowired
	private ContractClientService clientService;

	static final Log logger = LogFactory.getLog(ContractImportor.class);

	private Collection<String> missItems   = Lists.newArrayList();
	private Collection<String> missClients = Lists.newArrayList();
	private Collection<String> missNo = Lists.newArrayList();
	
	@Override
	public Map<String, Collection<ContractItem>> fromStream(InputStream input) {

		Map<String, Collection<ContractItem>> beans = Maps.newHashMap();

		HSSFWorkbook workbook = null;
		try {

			workbook = new HSSFWorkbook(input);

			int sheetNums = workbook.getNumberOfSheets();

			for (int s = 0; s < sheetNums; s++) {
				Sheet sheet = workbook.getSheetAt(s);
				Iterator<Row> rows = sheet.rowIterator();

				for (; rows.hasNext();) {
					Row row = rows.next();
					int rdx = row.getRowNum() + 1;
					if (rdx < 3)
						continue;
					Cell cell = null;
					String value = null;
					ContractItem item = new ContractItem();

					// code
					cell = row.getCell(2, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					// logger.info(rdx+"行,前产品代码:"+value);
					Product pdt = pdtService.getPrue(value);
					if (pdt == null) {
						Cell ncell = row.getCell(1,Row.CREATE_NULL_AS_BLANK);
						String nval = ExcelUtil.cellString(ncell);
						pdt = pdtService.getPureofName(nval);
						if (pdt == null) {
							String e = rdx + "行3列  产品代码 [" + value + "] 不存在,名称["+nval+"]不存在";
							logger.error(e);
							missItems.add(e);
							continue;
						}
					}
					// logger.info(pdt);
					item.setOwner(pdt);

					// client
					cell = row.getCell(3, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					ContractClient client = clientService.getByName(value);
					if (client == null) {
						String e = "行" + rdx + "列3 " + value
								+ " 客户不存在,请先添加客户信息";
						logger.error(e);
						missClients.add(e);
						continue;
					}
					item.setClient(client);

					// name
					cell = row.getCell(4, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					if (StringUtils.isBlank(value)) {
						String e = "行:" + rdx + "列: 4  合同编号必须存在";
						logger.error(e);
						missNo.add(e);
						continue;
					}
					Collection<ContractItem> items = beans.get(value);
					if (items == null) {
						items = Sets.newHashSet();
						beans.put(value, items);
					}

					// type
					cell = row.getCell(5, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					ContractType ctype;
					try {
						ctype = ContractType.valueOf(value);
					} catch (IllegalArgumentException ea) {
						ctype = ContractType.未知;
					}
					item.setContractType(ctype);

					// validation
					cell = row.getCell(6, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					ProductValidation validation;
					try {
						validation = ProductValidation.valueOf(value);
					} catch (IllegalArgumentException ea) {
						validation = ProductValidation.无校验;
					}
					item.setValidation(validation);

					// remark
					cell = row.getCell(7, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					TradeType ttype;
					try {
						ttype = TradeType.valueOf(value);
					} catch (IllegalArgumentException ea) {
						ttype = TradeType.未知;
					}
					item.setTradeType(ttype);

					// remark
					cell = row.getCell(8, Row.CREATE_NULL_AS_BLANK);
					value = ExcelUtil.cellString(cell);
					item.setRemark(value);

					// price
					cell = row.getCell(9, Row.CREATE_NULL_AS_BLANK);
					Double price = ExcelUtil.cellNumber(cell);
					item.setPrice(price);

					// storage
					cell = row.getCell(10, Row.CREATE_NULL_AS_BLANK);
					Double storage = ExcelUtil.cellNumber(cell);
					item.setStorage(storage);
					Collection<ContractDataItem> datas = Lists.newArrayList();

					for (int c = 11; c < 23; c++) {
						cell = row.getCell(c, Row.CREATE_NULL_AS_BLANK);
						Double assumpsit = 0D;
						if (cell != null) {
							assumpsit = ExcelUtil.cellNumber(cell);
						}
						ContractDataItem data = new ContractDataItem();
						data.setMonth(c - 11);
						data.setAssumpsit(assumpsit);
						datas.add(data);
					}
					item.setDataItems(datas);
					//logger.info(item + " added successfully!");
					items.add(item);
				}

			}
		} catch (IOException e) {
			logger.error(e);
			e.printStackTrace();
		}	
		return beans;
	}

	public Collection<String> getMissItems() {
		return missItems;
	}

	public Collection<String> getMissClients() {
		return missClients;
	}

	public Collection<String> getMissNo() {
		return missNo;
	}	
}
